package com.idm.tacacs.encryption;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.util.Properties;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class EncryptDecrypt {
	static Properties prop =null;
	public static void main(String[] args) throws Exception {

		prop = new Properties();
		try {
			//load a properties file
			//properties.load(new FileInputStream("path/filename"));
			prop.load(new FileInputStream("tacacsconfig.properties"));

		} catch (IOException ex) {
			ex.printStackTrace();
		}
		String strencrypt ="You can't cross the sea merely by standing and staring at the water";
		System.out.println("Input    :"+strencrypt);
		byte[] encrypt=encrypt(strencrypt);
		decrypt(encrypt);

	}

	public static byte[] decrypt(byte[] encrypted) throws Exception
	{
		String keyString = prop.getProperty("encryptionKey");
		Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
		byte[] iv =prop.getProperty("ivKey").getBytes();
		IvParameterSpec ivSpec = new IvParameterSpec(iv);
		// hash keyString with SHA-256 and crop the output to 128-bit for key
		MessageDigest digest = MessageDigest.getInstance("SHA-256");
		digest.update(keyString.getBytes());
		byte[] key = new byte[16];
		System.arraycopy(digest.digest(), 0, key, 0, key.length);
		SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
		cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
		byte[] decrypted = cipher.doFinal(encrypted);
		System.out.println("decrypted:" + new String(decrypted, "UTF-8"));
		return decrypted;
	}

	public  static byte[] encrypt(String input) throws Exception
	{

		String keyString = prop.getProperty("encryptionKey");
		// setup AES cipher in CBC mode with PKCS #5 padding
		Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
		byte[] iv =prop.getProperty("ivKey").getBytes();
		IvParameterSpec ivSpec = new IvParameterSpec(iv);
		// hash keyString with SHA-256 and crop the output to 128-bit for key
		MessageDigest digest = MessageDigest.getInstance("SHA-256");
		digest.update(keyString.getBytes());
		byte[] key = new byte[16];
		System.arraycopy(digest.digest(), 0, key, 0, key.length);
		SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
		cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
		byte[] encrypted = cipher.doFinal(input.getBytes("UTF-8"));
		System.out.println("encrypted:" + new String(encrypted));
		return encrypted;
	}
}